package fr.dauphine.bookstore.commun;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Session;

import fr.dauphine.bookstore.hibernate.HibernateUtil;
import fr.dauphine.bookstore.modele.Book;

/**
 * Photo d'un livre (sous forme d'image JPEG).
 */
public final class ImageServlet extends HttpServlet {

	/**
	 * Serial version UID.
	 */
	private static final long serialVersionUID = 6433394209725137522L;

	/**
	 * Traite la methode GET.
	 * 
	 * @param request
	 *            Requete
	 * @param response
	 *            Reponse
	 * @throws ServletException
	 *             Erreur de servlet
	 * @throws IOException
	 *             Erreur d'entree/sortie
	 */
	protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
		String id = request.getParameter("id");

		Session hSession = HibernateUtil.getSessionFactory().getCurrentSession();
		Book book = (Book) hSession.get(Book.class, Long.valueOf(id));

		if (book != null && book.getPhoto() != null) {
			response.setContentType("image/jpeg");
			response.getOutputStream().write(book.getPhoto());

		} else {
			response.sendError(HttpServletResponse.SC_NOT_FOUND);
		}
	}
}
